<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" 
	import="java.io.*" 
	import="java.util.*"
	import="javax.servlet.*" 
	import="org.json.simple.JSONObject"
	import="org.json.simple.parser.JSONParser"
	import="org.apache.commons.codec.binary.Base64"
	import="com.netcracker.studportal.server.facade.*"
%><%
	String materialID = request.getParameter("material_id");
	String userType = request.getParameter("user_type");

	if (materialID == null || userType == null) {
		return;
	}

	JSONObject jsonObj = null;
	if ("1".equals(userType) /* Student */) {
		FacadeStudent studentFacade = new FacadeStudent();
		JSONObject jsonParams = new JSONObject();
		jsonParams.put("material_id", materialID);

		String inputParams = jsonParams.toJSONString();
		String answer = studentFacade.loadMaterialByID(inputParams);

		JSONParser parser = new JSONParser();
		jsonObj = (JSONObject) parser.parse(answer);
	} else if ("2".equals(userType) /* Professor */) {
		FacadeProfessor professorFacade = new FacadeProfessor();
		JSONObject jsonParams = new JSONObject();
		jsonParams.put("material_id", materialID);

		String inputParams = jsonParams.toJSONString();
		String answer = professorFacade.loadMaterialByID(inputParams);

		JSONParser parser = new JSONParser();
		jsonObj = (JSONObject) parser.parse(answer);
	} else {
		out.print("Unsupported type of user = " + userType);
		return;
	}

	if (jsonObj != null && !jsonObj.containsKey("error")) {
		String fileName = jsonObj.get("file_name").toString();
		String fileContent = jsonObj.get("file_content").toString();
		byte[] byteArray = Base64.decodeBase64(fileContent);

		ServletOutputStream outStream = response.getOutputStream();
		response.setContentType("image/gif");
		response.setContentType("application/pdf");
		response.setContentType("application/download");
		response.setContentType("application/zip");
		response.setContentType("application/tar");
		response.setContentType("application/doc");
		response.setContentType("image/jpg");
		response.setContentType("application/word");
		response.setContentType("text/plain");
		response.setContentType("image/jpeg");
		response.setContentType("application/txt");
		response.setContentType("application/gif");
		response.setContentType("application/jpg");
		response.setContentType("text/html");
		response.setContentType("text/xml");
		response.setContentType("text/vap.wap.wml");
		response.setContentType("text,vnd.wap.xml");
		response.setContentType("text/vnd.wap.wml");
		response.setContentType("multipart/mixed");
		response.setContentType("text/html;charset=iso-2022-jp");
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition",
				"attachment; filename=\"" + fileName + "\"");

		outStream.write(byteArray);

		outStream.close();
	} else {
		String error = jsonObj.get("error").toString();
		out.print("Error: " + error);
	}
%>